<?php

namespace Vozminoski\StoreBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;
use Vozminoski\StoreBundle\Entity\Address;
use Vozminoski\StoreBundle\Form\AddressType;
use Vozminoski\StoreBundle\Entity\Orders;
use Vozminoski\StoreBundle\Entity\OrderItems;


class DefaultController extends Controller
{
    /**
     * @Route("/", name="home")
     * @Template()
     */
    public function homeAction()
    {
        $response = $this->forward('VozminoskiStoreBundle:Default:category', array('url' => null));
        return $response;
    }

    /**
     * @Route("/category/{url}/", name="catalog")
     * @Template()
     */
    public function categoryAction($url)
    {
        $em = $this->getDoctrine()->getManager();
        $categories = $em->getRepository('VozminoskiStoreBundle:Catalog')->findBy(
            array('is_active' => true),
            array('order' => 'ASC')
        );

        if (!$categories) {
            throw $this->createNotFoundException('Unable to find Categories.');
        }

        if ($url) {
            $category = $em->getRepository('VozminoskiStoreBundle:Catalog')->findByUrl($url);
            $category = is_array($category) ? $category[0] : null;
        } else {
            $category = $categories[0];
        }

        if (!$category) {
            throw $this->createNotFoundException('Unable to find Category.');
        }

        $products = $em->getRepository('VozminoskiStoreBundle:Product')->findBy(
            array('is_active' => true, 'category' => $category),
            array('order' => 'ASC')
        );

        $productWasAdded = $this->getRequest()->query->get('product_was_added');

        return array(
            'cart' => $this->getCart(),
            'categories' => $categories,
            'categoryUrl' => $category->getUrl(),
            'products' => $products,
            'product_was_added' => $productWasAdded
        );
    }

    /**
     * @Route("/about", name="about")
     * @Template()
     */
    public function aboutAction()
    {
        return array(
            'cart' => $this->getCart(),
        );
    }

    /**
     * @Route("/delivery", name="delivery")
     * @Template()
     */
    public function deliveryAction()
    {
        return array(
            'cart' => $this->getCart(),
        );
    }

    /**
     * @Route("/cart/delete/{number}/", name="delete_cart_item")
     */
    public function deleteFromCartAction($number)
    {
        $cart = $this->getCart();
        unset($cart[$number]);
        $this->get('session')->set('cart', array_values($cart));
        return $this->redirect($this->generateUrl('cart'));
    }


    /**
     * @Route("/cart/add", name="add_to_cart")
     */
    public function addToCartAction()
    {
        $request = $this->getRequest();

        $em = $this->getDoctrine()->getManager();
        $product = $em->getRepository('VozminoskiStoreBundle:Product')->find($request->request->get('product_id'));
        if (!$product) {
            throw $this->createNotFoundException('Unable to find Product entity.');
        }

        $itemsParams = array(
            'product_id' => $request->request->get('product_id'),
            'size' => $request->request->get('size'),
            'color' => $request->request->get('color'),
            'count' => $request->request->get('count'),
        );

        $cart = $this->getCart();
        $isCartHaveSaveProduct = false;
        foreach($cart as $key => $currentItem) {
            if ($currentItem['product_id'] == $itemsParams['product_id']
                && $currentItem['product_id'] == $itemsParams['product_id']
                && $currentItem['size'] == $itemsParams['size']
                && $currentItem['color'] == $itemsParams['color']
            ) {
                $cart[$key]['count'] += $itemsParams['count'];
                $isCartHaveSaveProduct = true;
                break;
            }
        }
        if (!$isCartHaveSaveProduct) {
            $cart[] = $itemsParams;
        }
        $this->get('session')->set('cart', $cart);
        return $this->redirect(
            $this->generateUrl('catalog', array('url' => $product->getCategory()->getUrl(), 'product_was_added' => 1 ))
            . '#small-product-' . $product->getId()
        );
    }


    /**
     * @Route("/cart", name="cart")
     * @Template()
     */
    public function cartAction()
    {
        $cart = $this->getCart();

        $cartsIds = array();
        foreach ($cart as $cartItemInfo) {
            $cartsIds[] = $cartItemInfo['product_id'];
        }

        $em = $this->getDoctrine()->getManager();
        $totalPrice = 0;

        if ($cartsIds) {
            $products = $em->getRepository('VozminoskiStoreBundle:Product')->findBy(
                array('id' => $cartsIds)
            );

            $productsSortByIds = array();
            foreach ($products as $product ) {
                $productsSortByIds[$product->getId()] = $product;
            }

            foreach ($cart as $key => $cartItemInfo) {
                if (array_key_exists($cartItemInfo['product_id'], $productsSortByIds)) {
                    $product = $productsSortByIds[$cartItemInfo['product_id']];
                    $cart[$key]['product'] = $product;
                    $totalPrice += $product->getPricePerNumberItems($cartItemInfo['count']);
                } else {
                    unset ($cart[$key]);
                }
            }

        }

        $addressForm = $this->createForm(new AddressType(), new Address());

        return array(
            'cart' => $cart,
            'totalPrice' => $totalPrice,
            'addressForm' => $addressForm->createView()
        );
    }

    /**
     * @Route("/thanks", name="thanks_page")
     * @Template()
     */
    public function thanksAction()
    {
        $this->get('session')->set('cart', array());

        return array(
            'cart' => $this->getCart(),
        );
    }

    /**
     * @Route("/payment/result", name="payment_result")
     */
    public function resultAction(Request $request)
    {
         // получаем номер транзакции
        $id = intval($request->request->get('InvId'));
        $em = $this->getDoctrine()->getManager();
        $order = $em->getRepository('VozminoskiStoreBundle:Orders')->find($id);

        $outSum = $request->request->get('OutSum');
        $signatureValue = $request->request->get('SignatureValue');

        if ( $order == null ) {
            $response = "ERR: invalid order id";
        } elseif ( $order->getTotalPrice() != floatval($outSum) ) {
            $response = "ERR: invalid amount";
        } elseif ( strtolower($signatureValue) != strtolower(md5("{$outSum}:{$id}:!LjrnjhPkjq81!")) ) {
            $response= "ERR: invalid signature";
        } else {
            $response = "OK" . $id;
            $order->setStatus(Orders::STATUS_PAID);
            $em->persist($order);
            $em->flush();

            $message = \Swift_Message::newInstance()
                ->setSubject('Order has been paid')
                ->setFrom('message@vozminoski.ru')
                ->setTo('vozminoski@gmail.com')
                ->setBody($this->renderView('VozminoskiStoreBundle:Default:email_paid.txt.twig', array('entity' => $order)));
            $this->get('mailer')->send($message);

        }
        return new Response($response);
    }

    /**
     * @Route("/payment/error", name="payment_error")
     * @Template()
     */
    public function errorAction()
    {
        return array(
            'cart' => $this->getCart(),
        );
    }

    /**
     * @Route("/purchase", name="purchase")
     */
    public function purchaseAction(Request $request)
    {
        $address  = new Address();
        $form = $this->createForm(new AddressType(), $address);
        $form->bind($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($address);
            $em->flush();

            $order = new Orders;

            $order->setAddress($address);
            $order->setTotalPrice(0.0);
            $order->setStatus(Orders::STATUS_PENDING);
            $order->setPaymentType($request->request->get('payment_type'));
            $order->setCreatedAt(new \DateTime('now'));

            $em->persist($order);
            $em->flush();

            $orderItems = $request->request->get('items');

            $totalPrice = 0;

            foreach ($orderItems as $orderData) {
                $itemEntity = new OrderItems();
                $product = $em->getRepository('VozminoskiStoreBundle:Product')->find($orderData['product_id']);
                $itemEntity->setProduct($product);
                $itemEntity->setOrder($order);
                $color = $em->getRepository('VozminoskiStoreBundle:Color')->find($orderData['color']);
                $itemEntity->setColor($color);
                $size = $em->getRepository('VozminoskiStoreBundle:Size')->find($orderData['size']);
                $itemEntity->setSize($size);
                $itemEntity->setCount($orderData['count']);
                $totalPrice += $product->getPricePerNumberItems($itemEntity->getCount());
                $em->persist($itemEntity);
            }

            $order->setTotalPrice($totalPrice);
            $em->persist($order);

            $em->flush();

            $em->refresh($order);

            $message = \Swift_Message::newInstance()
                ->setSubject('New order')
                ->setFrom('message@vozminoski.ru')
                ->setTo('vozminoski@gmail.com')
                ->setBody($this->renderView('VozminoskiStoreBundle:Default:email.txt.twig', array('entity' => $order)));
            $this->get('mailer')->send($message);

            if ($order->getPaymentType() == 1) {
                return $this->redirect($this->generateUrl('robokassa', array('orderId' => $order->getId())));
            } else {
                return $this->redirect($this->generateUrl('thanks_page'));
            }

        }

        return $this->redirect($this->generateUrl('cart'));
    }


    /**
     * @Route("/robokassa/{orderId}/", name="robokassa")
     * @Template()
     */
    public function robokassaAction($orderId)
    {
        $em = $this->getDoctrine()->getManager();
        $order = $em->getRepository('VozminoskiStoreBundle:Orders')->find($orderId);
        $login = 'dvynograd';
        $amount = floatval($order->getTotalPrice());
        $id = $order->getId();

        return array(
            'login' => $login,
            'amount' => $amount,
            'oderId' => $id,
            'signature' => md5("{$login}:{$amount}:{$id}:!stereo81!")
        );
    }

    /**
     * Get Cart
     * @return array
     */
    protected function getCart()
    {
        $cart = $this->get('session')->get('cart');
        return is_array($cart) ? $cart : array();
    }
}
